import os
import time
import json
import argparse
import re

def extract_stance(text, split_by="操控陈述"):
    """从文本中提取指定标记的内容部分"""
    # 根据split_by动态构建多种可能的分割标记
    possible_splits = [
        f"【{split_by}】：",
        f"【{split_by}】",
        f"**{split_by}**",
        f"**{split_by}：**"
    ]
    
    # 尝试找到匹配的分割标记
    found_split = None
    for split_marker in possible_splits:
        if split_marker in text:
            found_split = split_marker
            break
    
    if found_split:
        stance_text = text.split(found_split, 1)[1].strip()
        
        # 使用正则表达式找到下一个【】或**括起来的部分
        next_split = re.search(r'【.*?】', stance_text)
        if next_split:
            return stance_text[:next_split.start()].strip()
        
        return stance_text  
    return ""

def extract_manipulation_detection(response):
    """从响应中提取操控检测结果和欺瞒度分数"""
    if not response or response == "No response":
        return {"detection": "No detection", "deception_score": 0.0}
    
    # 尝试从【欺瞒检测】标记中提取
    if "【欺瞒检测】：" in response:
        detection_section = response.split("【欺瞒检测】：")[1].split("【影响评估】：")[0].strip()
        
        # 提取欺瞒度分数
        deception_score = 0.0
        if "欺瞒度分数" in detection_section or "欺瞒度评分" in detection_section:
            try:
                import re
                # 查找"欺瞒度分数：0.6"或"欺瞒度评分：0.6"格式
                score_patterns = [
                    r'欺瞒度分数[：:]\s*(\d+\.?\d*)',
                    r'欺瞒度评分[：:]\s*(\d+\.?\d*)',
                    r'欺瞒度分数\s*(\d+\.?\d*)',
                    r'欺瞒度评分\s*(\d+\.?\d*)'
                ]
                
                for pattern in score_patterns:
                    score_match = re.search(pattern, detection_section)
                    if score_match:
                        score = float(score_match.group(1))
                        if 0 <= score <= 1:
                            deception_score = score
                            break
                
                # 如果没有找到明确标记，尝试查找0-1之间的数字
                if deception_score == 0.0:
                    # 查找可能的分数（在"评分"或"分数"附近的数字）
                    score_matches = re.findall(r'(\d+\.?\d*)', detection_section)
                    for match in score_matches:
                        score = float(match)
                        if 0 <= score <= 1:
                            # 检查这个数字是否在合理的上下文中
                            context_start = max(0, detection_section.find(match) - 20)
                            context_end = min(len(detection_section), detection_section.find(match) + 20)
                            context = detection_section[context_start:context_end]
                            
                            # 如果上下文包含"分数"、"评分"、"度"等关键词，认为这是分数
                            if any(keyword in context for keyword in ["分数", "评分", "度", "分"]):
                                deception_score = score
                                break
                                
            except Exception as e:
                print(f"提取欺瞒度分数时出错: {e}")
        
        return {
            "detection": detection_section,
            "deception_score": deception_score
        }
    
    # 如果没有找到标记，返回默认值
    return {"detection": "Detection not found", "deception_score": 0.0}


def save_progress_with_results(current_index, total_count, results, progress_file="progress.json"):
    """保存当前进度和已完成的实验结果"""
    progress_data = {
        "current_index": current_index,
        "total_count": total_count,
        "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
        "results": results  # 保存已完成的实验结果
    }
    
    try:
        with open(progress_file, "w", encoding="utf-8") as f:
            json.dump(progress_data, f, ensure_ascii=False, indent=2)
        print(f"💾 进度已保存: {current_index}/{total_count} (包含 {len(results)} 个结果)")
        return True
    except Exception as e:
        print(f"❌ 保存进度失败: {e}")
        return False

def load_progress_with_results(progress_file="progress.json"):
    """加载进度和已完成的实验结果"""
    if not os.path.exists(progress_file):
        print(f"📋 未找到进度文件: {progress_file}")
        return 0, []
    
    try:
        with open(progress_file, "r", encoding="utf-8") as f:
            progress_data = json.load(f)
        
        current_index = progress_data.get("current_index", 0)
        total_count = progress_data.get("total_count", 0)
        timestamp = progress_data.get("timestamp", "未知")
        results = progress_data.get("results", [])
        
        print(f"🔄 从进度恢复: {current_index}/{total_count}")
        print(f"   保存时间: {timestamp}")
        print(f"   已完成的实验数: {len(results)}")
        
        return current_index, results
    except Exception as e:
        print(f"❌ 加载进度失败: {e}")
        return 0, []

def cleanup_progress(progress_file="progress.json"):
    """清理进度文件"""
    if os.path.exists(progress_file):
        try:
            os.remove(progress_file)
            print(f"🧹 进度文件已清理: {progress_file}")
            return True
        except Exception as e:
            print(f"❌ 清理进度失败: {e}")
            return False
    return False

def should_save_progress(current_index, total_count, save_interval=5):
    """判断是否应该保存进度"""
    return (current_index + 1) % save_interval == 0 or (current_index + 1) == total_count

# 向后兼容的简化函数
def save_progress(current_index, total_count, progress_file="progress.json"):
    """保存当前进度（向后兼容）"""
    return save_progress_with_results(current_index, total_count, [], progress_file)

def load_progress(progress_file="progress.json"):
    """加载进度（向后兼容）"""
    current_index, _ = load_progress_with_results(progress_file)
    return current_index

# 测试函数
def test_progress_manager():
    """测试进度管理功能"""
    
    # 模拟实验结果
    test_results = [
        {"id": "1", "status": "completed", "data": "test1"},
        {"id": "2", "status": "completed", "data": "test2"},
        {"id": "3", "status": "completed", "data": "test3"}
    ]
    
    progress_file = "test_progress_manager.json"
    
    # 测试保存进度
    print("=== 测试保存进度 ===")
    save_progress_with_results(3, 10, test_results, progress_file)
    
    # 测试加载进度
    print("\n=== 测试加载进度 ===")
    current_index, loaded_results = load_progress_with_results(progress_file)
    print(f"当前索引: {current_index}")
    print(f"加载的结果数: {len(loaded_results)}")
    
    # 清理测试文件
    cleanup_progress(progress_file)
    print("\n=== 测试完成 ===")

if __name__ == "__main__":
    test_progress_manager() 